<template>
  <div class="mistake-management-container">
    <div class="header">
      <h2 class="page-title">错题管理</h2>
      <el-input
        v-model="searchQuery"
        placeholder="搜索错题"
        prefix-icon="Search"
        class="search-input"
        @input="searchMistakes"
      />
    </div>

    <div class="content-wrapper">
      <div class="sidebar">
        <el-menu class="custom-menu">
          <el-menu-item @click="loadMistakes" class="menu-item">
            <template #title>
              <div class="menu-item-content">
                <span class="menu-title">我的错题</span>
                <span class="mistake-count">{{ mistakes.length }}道错题</span>
              </div>
            </template>
          </el-menu-item>
        </el-menu>
      </div>

      <div class="main-content">
        <div v-if="mistakes.length > 0">
          <el-tabs v-model="activeTab" type="card" class="custom-tabs">
            <el-tab-pane
              v-for="(mistake, index) in mistakes"
              :key="mistake.id"
              :label="`错题 ${index + 1}`"
              class="tab-pane"
            >
              <div class="mistake-card">
                <div class="question-header">
                  <span class="question-type">{{ getQuestionTypeText(mistake.type) }}</span>
                  <span class="question-score">{{ mistake.score }}分</span>
                </div>
                <div class="question-stem">{{ mistake.content }}</div>

                <div v-if="mistake.type === 'single' || mistake.type === 'multiple'">
                  <el-radio-group
                    v-model="userAnswers[mistake.questionId]"
                    v-if="mistake.type === 'single'"
                    class="options-group"
                  >
                    <el-radio
                      v-for="(option, idx) in JSON.parse(mistake.options)"
                      :key="idx"
                      :label="option.content"
                      class="option-item"
                    >
                      <span class="option-label">{{ String.fromCharCode(65 + idx) }}</span>
                      <span class="option-content">{{ option.content }}</span>
                    </el-radio>
                  </el-radio-group>
                  <el-checkbox-group
                    v-model="userAnswers[mistake.questionId]"
                    v-if="mistake.type === 'multiple'"
                    class="options-group"
                  >
                    <el-checkbox
                      v-for="(option, idx) in JSON.parse(mistake.options)"
                      :key="idx"
                      :label="option.content"
                      class="option-item"
                    >
                      <span class="option-label">{{ String.fromCharCode(65 + idx) }}</span>
                      <span class="option-content">{{ option.content }}</span>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>

                <div v-if="mistake.userAnswer !== null" class="user-answer">
                  <div class="answer-title">你的答案：</div>
                  <div>{{ mistake.userAnswer || '未作答' }}</div>
                </div>

                <div class="correct-answer">
                  <div class="answer-title">正确答案：</div>
                  <div>{{ getCorrectAnswer(mistake) }}</div>
                </div>

                <div v-if="mistake.explanation" class="question-analysis">
                  <div class="analysis-title">题目解析：</div>
                  <div>{{ mistake.explanation }}</div>
                </div>

                <div class="mistake-actions">
                  <el-button type="primary" @click="openReviewDialog(mistake)">再练一遍</el-button>
                  <el-button type="danger" @click="deleteMistake(mistake.id)">删除错题</el-button>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div v-else class="empty-content">
          <el-empty description="暂无错题记录" />
        </div>
      </div>
    </div>

    <el-dialog
      v-model="reviewDialogVisible"
      title="错题重练"
      width="50%"
      class="review-dialog"
    >
      <div class="dialog-content">
        <div class="question-header">
          <span class="question-type">{{ getQuestionTypeText(currentReviewMistake.type) }}</span>
          <span class="question-score">{{ currentReviewMistake.score }}分</span>
        </div>
        <div class="question-stem">{{ currentReviewMistake.content }}</div>

        <div v-if="currentReviewMistake.type === 'single' || currentReviewMistake.type === 'multiple'">
          <el-radio-group
            v-model="reviewUserAnswer"
            v-if="currentReviewMistake.type === 'single'"
            class="options-group"
          >
            <el-radio
              v-for="(option, idx) in JSON.parse(currentReviewMistake.options)"
              :key="idx"
              :label="option.content"
              class="option-item"
            >
              <span class="option-label">{{ String.fromCharCode(65 + idx) }}</span>
              <span class="option-content">{{ option.content }}</span>
            </el-radio>
          </el-radio-group>
          <el-checkbox-group
            v-model="reviewUserAnswerMultiple"
            v-if="currentReviewMistake.type === 'multiple'"
            class="options-group"
          >
            <el-checkbox
              v-for="(option, idx) in JSON.parse(currentReviewMistake.options)"
              :key="idx"
              :label="option.content"
              class="option-item"
            >
              <span class="option-label">{{ String.fromCharCode(65 + idx) }}</span>
              <span class="option-content">{{ option.content }}</span>
            </el-checkbox>
          </el-checkbox-group>
        </div>

        <div v-if="currentReviewMistake.type === 'fill' || currentReviewMistake.type === 'calculation'">
          <el-input
            v-model="reviewUserAnswer"
            :placeholder="`请输入${getQuestionTypeText(currentReviewMistake.type)}`"
            class="answer-input"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">提交答案</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { studentApi } from '@/api/studentApi';

export default defineComponent({
  setup() {
    const studentId = ref(1);
    const searchQuery = ref('');
    const mistakes = ref([]);
    const activeTab = ref(0);
    const userAnswers = ref({});
    const reviewDialogVisible = ref(false);
    const currentReviewMistake = ref(null);
    const reviewUserAnswer = ref('');
    const reviewUserAnswerMultiple = ref([]);

    const loadMistakes = async () => {
      try {
        const response = await studentApi.getMistakes(studentId.value);
        if (response.code === 200) {
          mistakes.value = response.data;
        } else {
          ElMessage.error(response.data.msg);
        }
      } catch (error) {
        console.error('获取学生错题列表失败:', error);
        ElMessage.error('获取学生错题列表失败');
      }
    };

    const searchMistakes = () => {
      if (searchQuery.value.trim() === '') {
        loadMistakes();
      } else {
        const filteredMistakes = mistakes.value.filter(mistake => {
          return mistake.content.includes(searchQuery.value);
        });
        mistakes.value = filteredMistakes;
      }
    };

    const getCorrectAnswer = (mistake) => {
      if (mistake.type === 'single' || mistake.type === 'multiple') {
        const options = JSON.parse(mistake.options);
        const correctOptions = options.filter(opt => opt.isCorrect).map(opt => opt.content);
        return mistake.type === 'single' ? correctOptions[0] : correctOptions.join(', ');
      } else if (mistake.type === 'fill') {
        try {
          const parsedBlanks = JSON.parse(mistake.blanks);
          const blanks = JSON.parse(parsedBlanks);
          return blanks[0].answer;
        } catch (error) {
          console.error('解析填空题答案失败:', error);
          return '解析填空题答案失败';
        }
      } else if (mistake.type === 'calculation') {
        try {
          const parsedAnswer = JSON.parse(mistake.answer);
          const answer = JSON.parse(parsedAnswer);
          return answer.answer;
        } catch (error) {
          console.error('解析计算题答案失败:', error);
          return '解析计算题答案失败';
        }
      }
      return '无正确答案';
    };

    const getQuestionTypeText = (type) => {
      const typeMap = {
        'single': '单选题',
        'multiple': '多选题',
        'fill': '填空题',
        'calculation': '计算题'
      };
      return typeMap[type] || type;
    };

    const deleteMistake = async (mistakeId) => {
      try {
        const response = await studentApi.deleteMistake(studentId.value, mistakeId);
        if (response.code === 200) {
          ElMessage.success('错题删除成功');
          loadMistakes();
        } else {
          ElMessage.error(response.data.msg);
        }
      } catch (error) {
        console.error('删除错题失败:', error);
        ElMessage.error('删除错题失败');
      }
    };

    const openReviewDialog = (mistake) => {
      currentReviewMistake.value = { ...mistake };
      if (mistake.type === 'multiple') {
        reviewUserAnswerMultiple.value = [];
      } else {
        reviewUserAnswer.value = '';
      }
      reviewDialogVisible.value = true;
    };

    const submitReview = () => {
      if (!currentReviewMistake.value) return;

      let isCorrect = false;
      let correctAnswer = getCorrectAnswer(currentReviewMistake.value);

      if (currentReviewMistake.value.type === 'single') {
        const correctOptions = JSON.parse(currentReviewMistake.value.options).filter(opt => opt.isCorrect).map(opt => opt.content);
        isCorrect = reviewUserAnswer.value === correctOptions[0];
      } else if (currentReviewMistake.value.type === 'multiple') {
        const correctOptions = JSON.parse(currentReviewMistake.value.options).filter(opt => opt.isCorrect).map(opt => opt.content);
        isCorrect = reviewUserAnswerMultiple.value.length === correctOptions.length && reviewUserAnswerMultiple.value.every(val => correctOptions.includes(val));
      } else if (currentReviewMistake.value.type === 'fill' || currentReviewMistake.value.type === 'calculation') {
        isCorrect = reviewUserAnswer.value.trim() === correctAnswer.trim();
      }

      ElMessage({
        message: isCorrect ? '回答正确！' : `回答错误，正确答案是：${correctAnswer}`,
        type: isCorrect ? 'success' : 'error'
      });
      reviewDialogVisible.value = false;
    };

    onMounted(() => {
      loadMistakes();
    });

    return {
      studentId,
      searchQuery,
      mistakes,
      activeTab,
      userAnswers,
      loadMistakes,
      searchMistakes,
      getCorrectAnswer,
      getQuestionTypeText,
      deleteMistake,
      reviewDialogVisible,
      currentReviewMistake,
      reviewUserAnswer,
      reviewUserAnswerMultiple,
      openReviewDialog,
      submitReview
    };
  }
});
</script>

<style scoped>
/* 主容器样式 */
.mistake-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 头部样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.search-input {
  width: 300px;
}

/* 内容区域样式 */
.content-wrapper {
  display: flex;
  gap: 20px;
}

/* 侧边栏样式 */
.sidebar {
  width: 250px;
  flex-shrink: 0;
}

.custom-menu {
  border: none;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.menu-item {
  border-bottom: 1px solid #ebeef5;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.menu-title {
  font-weight: 500;
  color: #303133;
}

.mistake-count {
  font-size: 14px;
  color: #f56c6c;
}

/* 主要内容区域样式 */
.main-content {
  flex: 1;
}

/* 错题卡片样式 */
.mistake-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 问题标题样式 */
.question-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.question-type {
  font-weight: 500;
  color: #303133;
}

.question-score {
  color: #f56c6c;
}

/* 题目内容样式 */
.question-stem {
  margin-bottom: 15px;
  line-height: 1.6;
  color: #303133;
}

/* 选项样式 */
.options-group {
  margin-bottom: 15px;
}

.option-item {
  margin-bottom: 10px;
}

.option-label {
  font-weight: 500;
  margin-right: 10px;
}

/* 用户答案样式 */
.user-answer, .correct-answer, .question-analysis {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.answer-title, .analysis-title {
  font-weight: 500;
  margin-bottom: 5px;
  color: #303133;
}

/* 操作按钮样式 */
.mistake-actions {
  display: flex;
  gap: 10px;
}

/* 空内容提示样式 */
.empty-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

/* 对话框样式 */
.review-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.dialog-content {
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.answer-input {
  width: 100%;
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
